<template>
	<view class="page-address-edit gray-page">
		<!-- 快手不支持获取收货地址 -->
		<!-- #ifndef MP-KUAISHOU -->
			<view class="get-wechat-address flex-between-center" @tap="onGetWechatAddress">
				<view class="flex-center">
					<image class="wechat-icon mr-4" :src="'/static/other/' + providerIconSrc" mode="widthFix"></image>
					<text>获取收货地址</text>
				</view>
				<image class="arrow-right" src="/static/other/arrow-right.svg" mode="widthFix"></image>
			</view>
		<!-- #endif -->
		
		<view class="main-field">
			<view class="field-item">
				<view class="field-title">收货人</view>
				<u-input v-model="form.userName" border="none" placeholder="收货人姓名" fontSize="14px"
					color="#000"></u-input>
			</view>
			<view class="field-item">
				<view class="field-title">手机号码</view>
				<u-input v-model="form.telNumber" border="none" placeholder="收货人手机号" fontSize="14px"
					color="#000"></u-input>
			</view>
			<view class="field-item" @click="onShowReginPicker">
				<view class="field-title">所在地区</view>
				<u-input v-model="form.region" disabled disabledColor="#ffffff" placeholder="选择省/市/区" border="none"
					ontSize="14px" color="#000"></u-input>

				<u-icon name="arrow-right" color="rgba(166, 166, 166, 1)"></u-icon>

			</view>
			<region-picker :value="selectedRegionArr" :show="showReginPicker" @close="onCloseReginPicker"
				@confirm="onSelectRegion" />

			<view class="field-item no-border-bottom">
				<view class="field-title">详细地址</view>
				<u-input v-model="form.detailInfo" border="none" placeholder="请填写详细地址" fontSize="14px"
					color="#000"></u-input>
			</view>




		</view>
		<view class="main-field">
			<view class="field-item no-border-bottom">
				<view class="normal-title">设为默认收货地址</view>
				<u-switch v-model="form.isDefault" @change="onIsDefaultChange"></u-switch>
			</view>
		</view>

		<view class="custom-button full-button" @tap="onSaveAndUse">
			<u-button type="primary" shape="circle" text="保存并使用"></u-button>
		</view>
		<view v-if="isEdit" class="custom-button white-btn full-button" @tap="onDelAddress">
			<u-button type="primary" shape="circle" text="删除收货地址"></u-button>
		</view>
	</view>

	<u-modal :show="confirmModal.show" :showCancelButton="true" :closeOnClickOverlay="true" @confirm="onConfirm"
		@cancel="onCancel">

		<view style="text-align: center;">
			<rich-text :nodes="confirmModal.content"></rich-text>
		</view>

	</u-modal>


</template>

<script setup>
	import {
		ref,
		shallowRef,
		reactive,
	} from "vue";
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import RegionPicker from '@/components/region-picker/index.vue';
	import { getProviderIconSrc } from '@/common/js/method.js';

	const form = reactive({
		region: '',
		userName: "",
		telNumber: "",
		detailInfo: "",
		isDefault: false
	});
	const addressId = ref('');
	const isEdit = ref(false);
	const showReginPicker = ref(false);
	const selectedRegionArr = shallowRef([]);
	const confirmModal = reactive({
		show: false,
		content: '',
	});
	const providerIconSrc = getProviderIconSrc();
	
	
	onLoad((params) => {
		if (params.type === 'edit') {
			const data = JSON.parse(params.data);
			console.log(data);
			const {
				address,
				area,
				consignee,
				isDefault,
				phone,
				id,
			} = data;
			form.region = area;
			selectedRegionArr.value = area.split('/');
			form.userName = consignee;
			form.telNumber = phone;
			form.detailInfo = address;
			form.isDefault = isDefault === 1 ? true : false;
			isEdit.value = true;
			addressId.value = id;
		}
	});
	const onIsDefaultChange = async () => {
		console.log('isDefault', form.isDefault);
		await uni.$request('/api/user/address/default', {
			id: addressId.value,
			isDefault: Number(form.isDefault),
		})
	}
	const delAddress = async () => {
		const res = await uni.$request('/api/user/address/delete', {
			id: addressId.value
		})
	}
	const saveAddress = async () => {
		const address = form;
		const path = isEdit.value ? '/api/user/address/update' : '/api/user/address/add';
		const res = await uni.$request(path, {
			id: addressId.value,
			/**
			 * 详细地址
			 */
			address: address.detailInfo,
			/**
			 * 所在地区
			 */
			area: address.region,
			/**
			 * 收货人
			 */
			consignee: address.userName,
			/**
			 * 是否默认地址，0：不是，1：是
			 */
			isDefault: address.isDefault ? 1 : 0,
			/**
			 * 联系电话
			 */
			phone: address.telNumber,
		});

		return res;

	}
	const onGetWechatAddress = () => {
		uni.chooseAddress({
			success(res) {
				// cityName: "广州市",
				// countyName: "海珠区",
				// detailInfo: "新港中路397号",
				// errMsg: "chooseAddress:ok",
				// nationalCode: "510000",
				// postalCode: "510000",
				// provinceName: "广东省",
				// telNumber: "020-81167888",
				// userName: "张三",
				console.log('微信地址信息', res);
				if(!res.userName) return;
				// 回填表单
				const {
					userName,
					telNumber,
					provinceName,
					cityName,
					countyName,
					detailInfo
				} = res;
				form.userName = userName;
				form.telNumber = telNumber;
				selectedRegionArr.value = [provinceName, cityName, countyName];
				form.region = [provinceName, cityName, countyName].join('/');
				form.detailInfo = detailInfo;
			}
		})
	};
	const onCloseReginPicker = () => {
		showReginPicker.value = false;
	};
	const onShowReginPicker = () => {
		showReginPicker.value = true;
	};
	const onSelectRegion = (data) => {
		console.log('省市区数据', data);
		selectedRegionArr.value = data;
		form.region = data.join('/');
	};

	// 获取位置（先询问，首次）
	const getLocation = () => {
		// uni.authorize({
		// 	scope: 'scope.userLocation',
		// 	success: () => {
		// 		uni.getLocation({
		// 			geocode: true,
		// 			success(res) {
		// 				console.log('获取到的地址信息', res)
		// 				uni.$u.toast(res.address)
		// 			},
		// 			fail(res) {
		// 				uni.$u.toast(res.errMsg)
		// 			},
		// 		})
		// 	},
		// 	fail(res) {
		// 		uni.$u.toast(res.errMsg)
		// 	}
		// })
	}

	// 定位
	const onLocation = () => {
		uni.getSetting({
			success({
				authSetting
			}) {
				// 用户首次没有同意位置消息, 关闭了权限
				if (authSetting['scope.userLocation'] === false) {
					confirmModal.show = true;
					confirmModal.content = '您的位置消息权限未开启<br>点击确认去开启';
				} else { //
					getLocation();
				}
			},
		})
	}

	const onConfirm = () => {
		confirmModal.show = false;
		confirmModal.content = '';
		// 打开设置，等用户操作并返回
		uni.openSetting({
			success({
				authSetting
			}) {
				// 如果用户打开了位置信息
				if (authSetting['scope.userLocation'] === true) {
					getLocation();
				}
			}
		});
	}
	const onCancel = () => {
		confirmModal.show = false;
		confirmModal.content = '';
	}

	// 保存并使用
	const onSaveAndUse = async () => {
		const address = form;
		if(!address.userName) {
			uni.$u.toast('请输入收货人');
			return Promise;
		}
		if(!address.telNumber) {
			uni.$u.toast('请输入联系电话');
			return;
		}
		if(!address.region) {
			
			uni.$u.toast('请选择所在地区');
			return;
		}
		if(!address.detailInfo) {
			uni.$u.toast('请输入详细地址');
			return;
		}
		let res = await saveAddress();
	
		// 存储数据
		uni.setStorageSync('choosedAddresInfo', {
			id: addressId.value || res.data.id, //编辑有addressId,新增是接口返回的id
			address: address.detailInfo,
			area: address.region,
			consignee: address.userName,
			phone: address.telNumber,
		})
		uni.navigateBack({
			delta: 2,
		})
	}
	// 删除收货地址
	const onDelAddress = async () => {
		await delAddress()
		uni.$u.toast('删除成功');
		uni.navigateBack({
			delta: 1,
		})
	}
</script>

<style lang="scss" scoped>
	.page-address-edit {
		padding: 20px 16px;
		display: flex;
		flex-direction: column;
		gap: 20px;

		.get-wechat-address {
			// height: 56px;
			border-radius: 8px;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.02);
			padding: 16px;

			.wechat-icon {
				width: 20px;
				height: 19px;
			}

			.arrow-right {
				width: 24px;
				height: 24px;
			}
		}


		.region-picker {
			height: 20px;
		}


		// .add-box {
		// 	box-sizing: border-box;
		// 	width: 100%;
		// 	background: #fff;
		// 	padding: 16px 16px 34px 16px;
		// 	position: fixed;
		// 	bottom: 0;
		// 	left: 0;
		// }
	}
</style>